package com.cscp.javastudy.juc.volatiledemo;


import java.util.concurrent.atomic.AtomicInteger;

/**
 * 总结：volatile不保证原子性
 * 原子性可以用Atomic去解决
 *
 */
public class VolatileDemo2 {

    private volatile static AtomicInteger num = new AtomicInteger();


    public static void main(String[] args) {
        //理论上结果等于20000
        for (int i = 1; i <=20; i++) {
            new Thread(()->{
                for (int j = 1; j <=1000; j++) {
                    add();
                }
            }).start();
        }

        while (Thread.activeCount()>2){
            Thread.yield();
        }

        System.out.println(Thread.currentThread().getName()+"结果是： "+num);
    }
    
    public static void add(){
        num.getAndIncrement();//AtomicInteger + 1的方法，CAS
    }

}
